﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using VM.Common.Result;

namespace VM.Common.http
{
    public class HttpReuestUtility
    {
        //private static readonly HttpClient _httpClient = new HttpClient();
        public static async Task<JsonObject> UploadFiles(string filePath, string jwtToken)
        {
            string apiUrl = "http://localhost:9004/api/files/upload"; // 替换成实际的接口地址
                                                                      // 将JWT Token添加到请求头中
            JsonObject reJson = new JsonObject();

            // 创建要上传的文件
            filePath = "d:/area.txt"; // 替换成实际的文件路径
            //byte[] fileContent = System.IO.File.ReadAllBytes(filePath);
            using (var httpClient = new HttpClient())
            {
                var request = new HttpRequestMessage(HttpMethod.Post, apiUrl);

                // 将JWT Token添加到请求头中
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);

                // 使用MultipartFormDataContent来上传文件和其他数据
                var formData = new MultipartFormDataContent();

                // 添加文件
                var fileContent = new StreamContent(File.OpenRead(filePath));
                formData.Add(fileContent, "file", Path.GetFileName(filePath));

                // 添加其他数据
                //formData.Add(new StringContent("Some data"), "key");

                // 将MultipartFormDataContent设置为请求体
                request.Content = formData;

                // 发送请求并等待响应
                var response = await httpClient.SendAsync(request);

                // 获取响应结果
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    reJson.code = 200;
                    reJson.msg = result;
                    //Console.WriteLine("文件上传成功！Result: " + result);
                }
                else
                {
                    var result = "文件上传失败！StatusCode: " + response.StatusCode;
                    reJson.code = 401;

                    reJson.msg = result;

                    //Console.WriteLine("文件上传失败！StatusCode: " + response.StatusCode);
                }
                return reJson;
            }


        }


        public static async Task<JsonObject> GetDataAsync(string url, string jwtToken)
        {
            using (var httpClient = new HttpClient())
            {
                JsonObject reJson = new JsonObject();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
                if (jwtToken != "")
                {
                    request.Headers.Add("Authorization", "Bearer " + jwtToken);
                }


                var response = await httpClient.SendAsync(request);
                //var response1 = response.IsSuccessStatusCode;


                if (response.IsSuccessStatusCode)
                {
                    string Res = await response.Content.ReadAsStringAsync();
                    JObject jo = (JObject)JsonConvert.DeserializeObject(Res);
                    reJson.code = Convert.ToInt32(jo["code"]);
                    reJson. Data= jo["data"];
                    reJson.msg = jo["msg"].ToString();

                }
                else
                {
                    var result = "获取列表失败！StatusCode: " + response.StatusCode;
                    reJson.code = 401;

                    reJson.msg = result;

                    //Console.WriteLine("文件上传失败！StatusCode: " + response.StatusCode);
                }

                return reJson;
            }

        }


        public static async Task<JsonObject> PostDataAsync(string url, string requestBody, string jwtToken)
        {

            using (var httpClient = new HttpClient())
            {
                JsonObject reJson = new JsonObject();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                if (jwtToken != "")
                {
                    request.Headers.Add("Authorization", "Bearer " + jwtToken);
                }
                var response = await httpClient.SendAsync(request);
                response.EnsureSuccessStatusCode();


                if (response.IsSuccessStatusCode)
                {
                    string Res = await response.Content.ReadAsStringAsync();
                    JObject jo = (JObject)JsonConvert.DeserializeObject(Res);
                    reJson.code = Convert.ToInt32(jo["code"]);
                    reJson.Data = jo["data"];
                    reJson.msg = jo["msg"].ToString();

                }
                else
                {
                    var result = "插入失败！StatusCode: " + response.StatusCode;
                    reJson.code = 401;

                    reJson.msg = result;

                    //Console.WriteLine("文件上传失败！StatusCode: " + response.StatusCode);
                }

                return reJson;




            }



        }



        /// <summary>
        /// 发送jason到服务器
        /// </summary>
        /// <param name="SendDate"></param>
        /// <param name="InterfaceName"></param>
        /// <returns></returns>
        public static JsonObject GetResponseData(string SendDate, string InterfaceName, string jwtToken = "", string ContentType = "application/json", string Accept = "application/json")
        {

            JsonObject reJson = new JsonObject();
            try
            {



                if (SendDate == "")
                {
                    SendDate = "{}";
                }



                byte[] bytes = Encoding.UTF8.GetBytes(SendDate);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InterfaceName);
                request.Method = "POST";

                //request.ContentType = "application/x-www-form-urlencoded";
                //request.Accept = "text/plain";
                request.ContentType = ContentType;// "application/json";
                request.Accept = Accept;//"application/json";
                request.ContentLength = bytes.Length;
                Stream reqstream = request.GetRequestStream();
                reqstream.Write(bytes, 0, bytes.Length);

                //声明一个HttpWebRequest请求  
                request.Timeout = 60000;
                //设置连接超时时间  
                request.Headers.Set("Prama", "no-cache");
                if (jwtToken != "")
                {
                    // 将JWT Token添加到请求头中
                    //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
                    request.Headers["Authorization"] = "Bearer " + jwtToken;
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream streamReceive = response.GetResponseStream();
                Encoding encoding = Encoding.UTF8;

                StreamReader streamReader = new StreamReader(streamReceive, encoding);
                string strResult = streamReader.ReadToEnd();
                streamReceive.Dispose();
                streamReader.Dispose();
                JObject JsonResult = JObject.Parse(strResult);
                int code = JsonResult["status"].Value<int>();
                string msg = JsonResult["msg"].Value<string>();
                string token = JsonResult["token"].Value<string>();
                string refreshToken = JsonResult["refreshToken"].Value<string>();
                //JArray jar = JArray.Parse(JsonResult["Data"].ToString());
                reJson.code = code;
                reJson.token = token;
                reJson.refreshtoken = refreshToken;


                reJson.msg = msg;
                reJson.Data = JsonResult["data"];


                return reJson;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static async Task<JsonObject> GetResponseDataAsync(string SendData, string InterfaceName, string jwtToken = "", string ContentType = "application/json", string Accept = "application/json")
        {
            JsonObject reJson = new JsonObject();
            try
            {
                if (SendData == "")
                {
                    SendData = "{}";
                }

                
                byte[] bytes = Encoding.UTF8.GetBytes(SendData);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InterfaceName);
                request.Method = "POST";
                request.ContentType = ContentType;
                request.Accept = Accept;
                request.ContentLength = bytes.Length;

                using (Stream reqstream = await request.GetRequestStreamAsync())
                {
                    await reqstream.WriteAsync(bytes, 0, bytes.Length);
                }

                //设置连接超时时间  
                request.Timeout = 60000;
                request.Headers.Set("Prama", "no-cache");
                if (jwtToken != "")
                {
                    request.Headers["Authorization"] = "Bearer " + jwtToken;
                }

                using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                {
                    using (Stream streamReceive = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(streamReceive, Encoding.UTF8))
                        {
                            string strResult = await streamReader.ReadToEndAsync();
                            JObject JsonResult = JObject.Parse(strResult);
                            int code = JsonResult["status"].Value<int>();
                            string msg = JsonResult["msg"].Value<string>();
                            string token = JsonResult["access_token"].Value<string>();
                            string refreshToken = JsonResult["refresh_token"].Value<string>();

                            reJson.code = code;
                            reJson.token = token;
                            reJson.refreshtoken = refreshToken;
                            reJson.msg = msg;
                            reJson.Data = JsonResult["data"];
                        }
                    }
                }

                return reJson;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static async Task<JsonObject> PostResponseDataAsync(string SendData, string InterfaceName, string jwtToken = "", string ContentType = "application/json", string Accept = "application/json")
        {
            JsonObject reJson = new JsonObject();
            try
            {
                if (SendData == "")
                {
                    SendData = "{}";
                }

                byte[] bytes = Encoding.UTF8.GetBytes(SendData);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InterfaceName);
                request.Method = "POST";
                request.ContentType = ContentType;
                request.Accept = Accept;
                request.ContentLength = bytes.Length;

                using (Stream reqstream = await request.GetRequestStreamAsync())
                {
                    await reqstream.WriteAsync(bytes, 0, bytes.Length);
                }

                //设置连接超时时间  
                request.Timeout = 60000;
                request.Headers.Set("Prama", "no-cache");
                if (jwtToken != "")
                {
                    request.Headers["Authorization"] = "Bearer " + jwtToken;
                }

                using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                {
                    using (Stream streamReceive = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(streamReceive, Encoding.UTF8))
                        {
                            string strResult = await streamReader.ReadToEndAsync();
                            JObject JsonResult = JObject.Parse(strResult);
                            int code = JsonResult["status"].Value<int>();
                            string msg = JsonResult["msg"].Value<string>();
                            string token = JsonResult["access_token"].Value<string>();
                            

                            reJson.code = code;
                            reJson.token = token;
                          
                            reJson.msg = msg;
                            reJson.Data = JsonResult["data"];
                        }
                    }
                }

                return reJson;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        /// <summary>
        /// 发送jason到服务器
        /// </summary>
        /// <param name="SendDate"></param>
        /// <param name="InterfaceName"></param>
        /// <returns></returns>
        public static JsonObject GetResponseDataByGet(string InterfaceName)
        {

            JsonObject reJson = new JsonObject();
            try
            {

                // byte[] bytes = Encoding.UTF8.GetBytes(SendDate);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(InterfaceName);
                request.Method = "GET";

                //request.ContentType = "application/x-www-form-urlencoded";
                //request.Accept = "text/plain";
                //request.ContentType = "application/json";
                //request.Accept = "application/json";
                //request.ContentLength = bytes.Length;
                //Stream reqstream = request.GetRequestStream();
                //  reqstream.Write(bytes, 0, bytes.Length);

                //声明一个HttpWebRequest请求  
                request.Timeout = 60000;
                //设置连接超时时间  
                request.Headers.Set("Pragma", "no-cache");
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream streamReceive = response.GetResponseStream();
                Encoding encoding = Encoding.UTF8;

                StreamReader streamReader = new StreamReader(streamReceive, encoding);
                string strResult = streamReader.ReadToEnd();
                streamReceive.Dispose();
                streamReader.Dispose();
                JObject JsonResult = JObject.Parse(strResult);
                int code = JsonResult["code"].Value<int>();
                string msg = JsonResult["msg"].Value<string>();
                string token = JsonResult["token"].Value<string>();
                string refreshToken = JsonResult["refreshToken"].Value<string>();
                //JArray jar = JArray.Parse(JsonResult["Data"].ToString());
                reJson.code = code;
                reJson.msg = msg;
                reJson.Data = JsonResult["data"];

                return reJson;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}